package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.nursing.domain.Elder;
import com.zzyl.nursing.domain.NursingTask;
import com.zzyl.nursing.dto.CancelTaskDto;
import com.zzyl.nursing.dto.DoTaskDto;
import com.zzyl.nursing.dto.UpdateTimeDto;
import com.zzyl.nursing.mapper.NursingTaskMapper;
import com.zzyl.nursing.service.INursingTaskService;
import com.zzyl.nursing.util.IDCardUtils;
import com.zzyl.nursing.vo.NusingTaskVo2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

import static com.zzyl.common.core.domain.AjaxResult.error;
import static com.zzyl.common.core.domain.AjaxResult.success;

/**
 * 护理任务Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-10-09
 */
@Service
public class NursingTaskServiceImpl extends ServiceImpl<NursingTaskMapper,NursingTask> implements INursingTaskService
{
    @Autowired
    private NursingTaskMapper nursingTaskMapper;

    @Autowired
    private ElderServiceImpl elderService;

    /**
     * 查询护理任务
     *
     * @param id 护理任务主键
     * @return 护理任务详情视图对象
     */
    @Override
    public NusingTaskVo2 selectNursingTaskById(Long id)
    {
        // 根据主键获取护理任务实体，若不存在则抛出异常
        NursingTask nursingTask = getById(id);
        if (nursingTask == null) {
            throw new BaseException("未找到ID为" + id + "的护理任务");
            // 或：return null;
        }

        // 拷贝属性到 VO 对象中
        NusingTaskVo2 nusingTaskVo2 = BeanUtil.copyProperties(nursingTask, NusingTaskVo2.class);

        // 查询并设置护理等级名称
        String nursingLevelName = nursingTaskMapper.queryLevel(nusingTaskVo2.getElderId());
        nusingTaskVo2.setNursingLevelName(nursingLevelName);

        // 解析护理项目 ID 字符串，并构造成列表用于批量查询名称
        String nursingId = nusingTaskVo2.getNursingId();
        List<String> nameList = new ArrayList<>();
        // 先判断 nursingId 是否为 null
        if (nursingId != null && nursingId.contains(",")) {
            String[] split = nursingId.split(",");
            for (String s : split) {
                nameList.add(s);
            }
        } else if (nursingId != null) { // 非 null 且不包含逗号的情况
            nameList.add(nursingId);
        }

        // 批量查询护理人员名称并设置
        List<String> nursingPersonnelNameList = nursingTaskMapper.queryLevelName(nameList);
        nusingTaskVo2.setNursingName(nursingPersonnelNameList);

        // 查询老人信息并校验是否存在
        Elder elder = elderService.lambdaQuery().eq(Elder::getId, nursingTask.getElderId()).one();
        if (elder == null) {
            // 方案：抛异常或设置默认值（根据业务需求）
            throw new BaseException("未找到ID为" + nursingTask.getElderId() + "的老人信息");
            // 或：return null; 并在 Controller 层处理
        }
        String idCard = elder.getIdCardNo(); // 此时 elder 非 null，安全调用

        // 获取老人性别与年龄并设置至返回结果中
        Map<String, Object> elderGenderAndAgeByIdCard = getElderGenderAndAgeByIdCard(idCard);
        nusingTaskVo2.setSex(elderGenderAndAgeByIdCard.get("gender").toString());
        nusingTaskVo2.setAge(Integer.valueOf(elderGenderAndAgeByIdCard.get("age").toString()));

        return nusingTaskVo2;
    }


    /**
     * 根据身份证号获取老人的性别和年龄
     * @param idCard 身份证号码
     * @return 包含性别和年龄信息的结果
     */
    public Map<String, Object> getElderGenderAndAgeByIdCard(String idCard) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 使用IDCardUtils.getAgeByIdCard方法获取年龄
            int age = IDCardUtils.getAgeByIdCard(idCard);

            // 使用IDCardUtils.getGenderFromIdCard方法获取性别
            int genderCode = IDCardUtils.getGenderFromIdCard(idCard);
            String gender = genderCode == 1 ? "男" : "女";

            result.put("age", age);
            result.put("gender", gender);

        } catch (Exception e) {
            throw new IllegalArgumentException("身份证号码无效: " + idCard, e);
        }
        return result;
    }

    /**
     * 查询护理任务列表
     * 
     * @param nursingTask 护理任务
     * @return 护理任务
     */
    @Override
    public List<NursingTask> selectNursingTaskList(NursingTask nursingTask)
    {
        List<NursingTask> nursingTasks = nursingTaskMapper.selectNursingTaskList(nursingTask);
        for (NursingTask task : nursingTasks) {
            String nursingId = task.getNursingId();
            List<String> nameList = new ArrayList<>();
            if(nursingId.contains(",")){
                String[] split = nursingId.split(",");
                for (String s : split) {
                    nameList.add(s);
                }
            }else {
                nameList.add(nursingId);
            }

            List<String> nursingPersonnelNameList = nursingTaskMapper.queryLevelName(nameList);

            task.setNursingName(nursingPersonnelNameList);
        }
        return nursingTasks;
    }

    /**
     * 新增护理任务
     * 
     * @param nursingTask 护理任务
     * @return 结果
     */
    @Override
    public int insertNursingTask(NursingTask nursingTask)
    {
        return save(nursingTask)?1:0;
    }

    /**
     * 修改护理任务
     * 
     * @param nursingTask 护理任务
     * @return 结果
     */
    @Override
    public int updateNursingTask(NursingTask nursingTask)
    {
        return updateById(nursingTask)?1:0;
    }

    /**
     * 批量删除护理任务
     * 
     * @param ids 需要删除的护理任务主键
     * @return 结果
     */
    @Override
    public int deleteNursingTaskByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids))?1:0;
    }

    /**
     * 删除护理任务信息
     * 
     * @param id 护理任务主键
     * @return 结果
     */
    @Override
    public int deleteNursingTaskById(Long id)
    {
        return removeById(id)?1:0;
    }




    /**
     * 取消护理任务
     *
     * @param dto 包含任务ID和取消原因的数据传输对象
     * @return AjaxResult 操作结果，成功返回成功信息，失败返回错误信息
     */
    @Override
    public AjaxResult cancelNursingTask(CancelTaskDto dto) {
        // 验证任务ID是否有效
        if (dto.getTaskId() == null || dto.getTaskId() <= 0) {
            return error("任务ID不能为空");
        }

        // 更新状态为已关闭（假设 status=3 表示已关闭）
        int result = nursingTaskMapper.updateStatusById(dto.getTaskId(), 3, dto.getReason());

        // 根据更新结果返回相应信息
        if (result > 0) {
            return success("操作成功");
        } else {
            return error("取消失败，请重试");
        }
    }







    /**
     * 执行护理任务
     *
     * @param dto 任务执行参数对象，包含任务ID、标记、预估服务时间、任务图片等信息
     * @return AjaxResult 执行结果，成功返回成功信息，失败返回错误信息
     */
    @Override
    public AjaxResult doNursingTask(DoTaskDto dto) {
        // 验证任务ID是否有效
        if (dto.getTaskId() == null || dto.getTaskId() <= 0) {
            return error("任务ID不能为空");
        }

        // 更新任务状态和执行信息
        int result = nursingTaskMapper.updateStatusAndExecuteInfo(dto.getTaskId(), 2, dto.getMark(), dto.getEstimatedServerTime(), dto.getTaskImage());

        // 根据更新结果返回相应信息
        if (result > 0) {
            return success("操作成功");
        } else {
            return error("执行失败，请重试");
        }
    }



    /**
     * 更新护理任务的执行时间
     *
     * @param dto 包含任务ID和预计执行时间的更新数据传输对象
     *            - taskId: 任务ID，必须大于0
     *            - estimatedServerTime: 预计执行时间，不能为空
     * @return AjaxResult 操作结果
     *         - 成功时返回成功消息
     *         - 失败时返回相应的错误消息
     */
    @Override
    public AjaxResult updateTaskTime(UpdateTimeDto dto) {
        // 验证任务ID是否有效
        if (dto.getTaskId() == null || dto.getTaskId() <= 0) {
            return error("任务ID不能为空");
        }

        // 验证执行时间是否为空
        if (dto.getEstimatedServerTime() == null || dto.getEstimatedServerTime().trim().isEmpty()) {
            return error("执行时间不能为空");
        }

        // 调用数据库更新操作
        int result = nursingTaskMapper.updateTaskTime(dto.getTaskId(), dto.getEstimatedServerTime());

        // 根据更新结果返回相应消息
        if (result > 0) {
            return success("操作成功");
        } else {
            return error("改期失败，请重试");
        }
    }


}


